package com.lechuang.songbo.view.activity.home;


import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.MemoryCategory;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.jude.rollviewpager.OnItemClickListener;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.ColorPointHintView;
import com.lechuang.songbo.R;
import com.lechuang.songbo.base.BaseFragment;
import com.lechuang.songbo.model.LeCommon;
import com.lechuang.songbo.model.bean.GetBean;
import com.lechuang.songbo.model.bean.HomeBannerBean;
import com.lechuang.songbo.model.bean.HomeKindBean;
import com.lechuang.songbo.model.bean.HomeLastProgramBean;
import com.lechuang.songbo.model.bean.HomeProgramBean;
import com.lechuang.songbo.model.bean.HomeScrollTextViewBean;
import com.lechuang.songbo.presenter.CommonAdapter;
import com.lechuang.songbo.presenter.ToastManager;
import com.lechuang.songbo.presenter.adapter.BannerAdapter;
import com.lechuang.songbo.presenter.adapter.HomeRecyclerAdapter;
import com.lechuang.songbo.presenter.net.Netword;
import com.lechuang.songbo.presenter.net.ResultBack;
import com.lechuang.songbo.presenter.net.netApi.HomeApi;
import com.lechuang.songbo.utils.Utils;
import com.lechuang.songbo.view.activity.SigneActivity;
import com.lechuang.songbo.view.activity.own.ApplyAgentActivity;
import com.lechuang.songbo.view.activity.own.InfoActivity;
import com.lechuang.songbo.view.activity.own.MyAgentActivity;
import com.lechuang.songbo.view.activity.recyclerView.ViewPagerForScrollView;
import com.lechuang.songbo.view.defineView.MGridView;
import com.lechuang.songbo.view.defineView.ViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.lechuang.songbo.R.id.gaotu;

/**
 * 作者：li on 2017/9/21 17:46
 * 邮箱：961567115@qq.com
 * 修改备注:
 */
public class HomeFragment extends BaseFragment {
    protected Subscription subscription;

    @BindView(R.id.tv_search)
    TextView tvSearch;         //搜索
    @BindView(R.id.gv_kind)
    MGridView gvKind;        //首页分类
    Unbinder unbinder;
    @BindView(R.id.iv_top)
    ImageView ivTop;        //回到顶部
    @BindView(R.id.ll_noNet)
    LinearLayout llNoNet; //没有网络
    @BindView(R.id.iv_tryAgain)
    ImageView tryAgain;
    @BindView(R.id.tablayout_home)
    TabLayout tablayoutHome;
    @BindView(R.id.iv_program1)
    ImageView ivProgram1;
    @BindView(R.id.iv_program2)
    ImageView ivProgram2;
    @BindView(R.id.iv_program3)
    ImageView ivProgram3;
    @BindView(R.id.iv_program4)
    ImageView ivProgram4;
    @BindView(R.id.ll_content)
    LinearLayout llContent;
    @BindView(R.id.rv_banner)
    RollPagerView rvBanner;
    @BindView(R.id.ll_program)
    LinearLayout llProgram;
    @BindView(R.id.vp_home)
    ViewPagerForScrollView vpHome;
    @BindView(R.id.tv_sign)
    TextView tv_sign;
    @BindView(R.id.rv_home)
    RecyclerView rvHome;


    private View v;
    private View contentView;

    private ArrayList<String> text = null;
    //轮播图
    private RollPagerView mRollViewPager;
    //最下栏目广告图
    private ImageView homeLastImg;
    //刷新重试
    //private ImageView tryAgain;
    private PullToRefreshScrollView refreshScrollView;
    private ScrollView scrollView;
    private SharedPreferences se;


    private int lastY = 0; //记录滑动位置
    boolean isVisible = false; //记录是否滑动显示
    //首页图标
    private int[] homeKindImg = {R.drawable.shouye_chaojiquan, R.drawable.shouye_chaojifan
            , R.drawable.shouye_shishixiaoliang, R.drawable.shouye_kefu
            , R.drawable.shouye__qiandaoshaidan, R.drawable.shouye_shengqingdaili
            , R.drawable.shouye_jingpintuijian, R.drawable.shouye_zhibojian};
    //首页类目名称
    private String[] homeKindName = {"超级券", "超级返", "实时销量", "客服", "签到", "申请代理", "精品推荐", "直播间"};
    private int[] position = new int[2];
    //记录gaotu  的位置
    private int i;
    private View.OnTouchListener onTouchListener;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, v);
        initView();
        initEvent();
        getData();
        se = PreferenceManager.getDefaultSharedPreferences(getActivity());
        return v;
    }

    //网络获取数据
    private void getData() {
        //showWaitDialog("");
        if (Utils.isNetworkAvailable(getActivity())) {
            refreshScrollView.setVisibility(View.VISIBLE);
            llNoNet.setVisibility(View.GONE);
            //获取首页轮播图数据
            getHomeBannerData();
            //首页分类数据
            getHomeKindData();
            //首页滚动文字数据
            // getHomeScrollTextView();
            //首页4个图片栏目数据
            getHomeProgram();
            //首页最下栏目数据
            lastData();
            //隐藏加载框
            hideWaitDialog();
        } else {
            //隐藏加载框
            hideWaitDialog();
            llNoNet.setVisibility(View.VISIBLE);//刷新重试
            refreshScrollView.setVisibility(View.GONE);
            showShortToast(getString(R.string.net_error));
        }

    }


    private void initView() {
        homeLastImg = (ImageView) v.findViewById(R.id.iv_last_img);
        refreshScrollView = (PullToRefreshScrollView) v.findViewById(R.id.refreshScrollView);
        scrollView = refreshScrollView.getRefreshableView();
        //轮播图
        mRollViewPager = (RollPagerView) v.findViewById(R.id.rv_banner);
        //refreshScrollView最上方显示,防止refreshScrollView初始化时不在最上方
        //获取焦点  必须先获取焦点才能在顶部  另外内部的listview gridView不能有焦点
        refreshScrollView.setFocusable(true);
        refreshScrollView.setFocusableInTouchMode(true);
        refreshScrollView.requestFocus();
        refreshScrollView.getRefreshableView().scrollTo(0, 0);

    }

    private void initEvent() {
        //tryAgain = (ImageView) v.findViewById(R.id.tryAgain);

        //刷新监听
        refreshScrollView.setOnRefreshListener(refresh);
        refreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        if (contentView == null) {
            contentView = scrollView.getChildAt(0);
        }
        scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                vpHome.getLocationOnScreen(position);
                changeVeiw();
            }
        });
        //监听ScrollView滑动停止
        scrollView.setOnTouchListener(onTouchListener = new View.OnTouchListener() {


            private int touchEventId = -9983761;

            Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    View scroller = (View) msg.obj;
                    if (msg.what == touchEventId) {
                        if (lastY == scroller.getScrollY()) {
                            handleStop(scroller);
                        }
                        //根据gaotu来判断Tablayout的显示与否
                        lastY = scroller.getScrollY();

                    }
                }
            };


            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_MOVE || event.getAction() == MotionEvent.ACTION_UP) {
                    //置顶按钮，时时监控
                    vpHome.getLocationOnScreen(position);
                    handler.sendMessageDelayed(
                            handler.obtainMessage(touchEventId, v), 5);

                }


                return false;
            }

            private void handleStop(Object view) {
                doOnBorderListener();
            }
        });
    }

    private void changeVeiw() {
        i = position[1];
        if (i < 300) {
            if (!isVisible) {
                tablayoutHome.setVisibility(View.VISIBLE);

              /*  llProgram.setVisibility(View.GONE);
                rvBanner.setVisibility(View.GONE);
                gvKind.setVisibility(View.GONE);*/
              /*  ivTop.setVisibility(View.VISIBLE);*/
                vpHome.isScroll = true;
                isVisible = true;
            }
        } else {
            if (isVisible) {
                tablayoutHome.setVisibility(View.GONE);
              /*  llProgram.setVisibility(View.VISIBLE);
                rvBanner.setVisibility(View.VISIBLE);
                gvKind.setVisibility(View.VISIBLE);*/
                vpHome.isScroll = false;
                isVisible = false;
            }


        }
    }

    private List<HomeBannerBean.IndexBannerList> bannerList;

    //获取首页轮播图数据
    private void getHomeBannerData() {
        //首页轮播图数据
        Netword.getInstance().getApi(HomeApi.class)
                .homeBanner()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<HomeBannerBean>(getActivity()) {

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();
                    }

                    @Override
                    public void successed(HomeBannerBean result) {
                        if (result == null) {
                            return;
                        }
                        bannerList = result.indexBannerList0;
                        List<String> imgList = new ArrayList<>();
                        for (int i = 0; i < bannerList.size(); i++) {
                            imgList.add(bannerList.get(i).img);
                        }
                        //设置播放时间间隔
                        mRollViewPager.setPlayDelay(3000);
                        //设置透明度
                        mRollViewPager.setAnimationDurtion(500);
                        //设置适配器
                        mRollViewPager.setAdapter(new BannerAdapter(getActivity(), imgList));
                        //设置指示器（顺序依次）
                        //自定义指示器图片
                        //设置圆点指示器颜色
                        //设置文字指示器
                        //隐藏指示器
                        //mRollViewPager.setHintView(new IconHintView(this, R.drawable.point_focus, R.drawable.point_normal));
                        mRollViewPager.setHintView(new ColorPointHintView(getActivity(), Color.YELLOW, Color.WHITE));
                        //mRollViewPager.setHintView(new TextHintView(this));
                        //mRollViewPager.setHintView(null);
                        mRollViewPager.setOnItemClickListener(new OnItemClickListener() {
                            @Override
                            public void onItemClick(int position) {
                                //获取到点击条目
                                int programaId = bannerList.get(position).programaId;
                                if (programaId == 1) {
                                    //栏目1
                                    startActivity(new Intent(getActivity(), ProgramDetailActivity.class)
                                            .putExtra("programaId", 1));
                                } else if (programaId == 2) {
                                    //栏目2
                                    startActivity(new Intent(getActivity(), ProgramDetailActivity.class)
                                            .putExtra("programaId", 2));
                                } else if (programaId == 3) {
                                    //栏目3
                                    startActivity(new Intent(getActivity(), ProgramDetailActivity.class)
                                            .putExtra("programaId", 3));
                                } else if (programaId == 4) {
                                    //栏目4
                                    startActivity(new Intent(getActivity(), ProgramDetailActivity.class)
                                            .putExtra("programaId", 4));
                                } else if (programaId == 5) {
                                    //栏目5
                                    handler2.sendEmptyMessage(1);
                                } else {
                                    // TODO: 2017/10/1 跳转奔溃
                                    startActivity(new Intent(getActivity(), EmptyWebActivity.class)
                                            .putExtra("url", bannerList.get(position).link));
                                }
                            }
                        });
                    }
                });
    }

    //获取首页分类数据
    private void getHomeKindData() {
        //首页分类数据
        List<HomeKindBean> list = new ArrayList<>();
        for (int i = 0; i < homeKindImg.length; i++) {
            HomeKindBean bean = new HomeKindBean();
            bean.img = homeKindImg[i];
            bean.name = homeKindName[i];
            list.add(bean);
        }
        gvKind.setAdapter(new CommonAdapter<HomeKindBean>(getActivity(), list, R.layout.home_kinds_item) {
            @Override
            public void setData(ViewHolder viewHolder, Object item) {
                HomeKindBean bean = (HomeKindBean) item;
                //分类名称
                viewHolder.setText(R.id.tv_kinds_name, bean.name);
                //分类图片
                viewHolder.setImageResource(R.id.iv_kinds_img, bean.img);
            }
        });

        gvKind.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 5:                   //我的代理
                        if (se.getInt("isAgencyStatus", 0) == 1) {
                            startActivity(new Intent(getActivity(), MyAgentActivity.class));
                        } else {
                            startActivity(new Intent(getActivity(), ApplyAgentActivity.class));
                        }
                        break;
                    case 1:       //超级返
                        Intent intent = new Intent(getActivity(), KindDetailActivity.class);
                        intent.putExtra("type", 1);
                        //rootName传递过去显示在标题上
                        intent.putExtra("rootName", homeKindName[position]);
                        startActivity(intent);

                        break;
                    case 0:          //超级卷
                        Intent intent2 = new Intent(getActivity(), KindDetailActivity.class);
                        intent2.putExtra("type", 2);
                        //rootName传递过去显示在标题上
                        intent2.putExtra("rootName", homeKindName[position]);
                        startActivity(intent2);

                        break;
                    case 7:          //直播间
                        startActivity(new Intent(getActivity(), LiveActivity.class));
                        break;
                    case 4:         //签到晒单
                        startActivity(new Intent(getActivity(), SigneActivity.class));

                        break;
                    case 6:          //精品推荐
                        Intent intent3 = new Intent(getActivity(), KindDetailActivity.class);
                        intent3.putExtra("type", 3);
                        //rootName传递过去显示在标题上
                        intent3.putExtra("rootName", homeKindName[position]);
                        startActivity(intent3);

                        break;
                    case 2:            //实时销量
                        Intent intent4 = new Intent(getActivity(), KindDetailActivity.class);
                        intent4.putExtra("type", 4);
                        //rootName传递过去显示在标题上
                        intent4.putExtra("rootName", homeKindName[position]);
                        startActivity(intent4);
                        break;
                    case 3:          //客服
                        startActivity(new Intent(getActivity(), InfoActivity.class));
                        break;

                }
            }
        });
    }

    //首页滚动文字数据
    private void getHomeScrollTextView() {
        Netword.getInstance().getApi(HomeApi.class)
                .homeScrollTextView()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<HomeScrollTextViewBean>(getActivity()) {
                    @Override
                    public void successed(HomeScrollTextViewBean result) {
                        if (result == null) {
                            return;
                        }
                        final List<HomeScrollTextViewBean.ListBean> list = result.indexMsgList;
                        //滚动TextView
                        text = new ArrayList<>();
                        for (int i = 0; i < list.size(); i++) {
                            text.add(list.get(i).title);
                        }
                    }
                });
    }

    //首页4个图片栏目数据
    private void getHomeProgram() {
        Netword.getInstance().getApi(HomeApi.class)
                .homeProgramaImg()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<HomeProgramBean>(getActivity()) {
                    @Override
                    public void successed(HomeProgramBean result) {
                        if (result == null) {
                            return;
                        }
                        final List<HomeProgramBean.ListBean> list = result.programaImgList;
                        List<String> imgList = new ArrayList<>();
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i) != null)
                                imgList.add(list.get(i).img);
                        }
                        //栏目1
                        if (imgList.get(0) != null)
                            Glide.with(getActivity()).load(imgList.get(0)).into(ivProgram1);
                        //栏目2
                        if (imgList.get(1) != null)
                            Glide.with(getActivity()).load(imgList.get(1)).into(ivProgram2);
                        //栏目3
                        if (imgList.get(1) != null)
                            Glide.with(getActivity()).load(imgList.get(2)).into(ivProgram3);
                        //栏目4
                        if (imgList.get(1) != null)
                            Glide.with(getActivity()).load(imgList.get(3)).into(ivProgram4);
                        ivProgram1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(getActivity(), ProgramDetailActivity.class)
                                        .putExtra("programaId", list.get(0).programaId));
                            }
                        });
                        ivProgram2.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(getActivity(), ProgramDetailActivity.class)
                                        .putExtra("programaId", list.get(1).programaId));
                            }
                        });
                        ivProgram3.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(getActivity(), ProgramDetailActivity.class)
                                        .putExtra("programaId", list.get(2).programaId));
                            }
                        });
                        ivProgram4.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                startActivity(new Intent(getActivity(), ProgramDetailActivity.class)
                                        .putExtra("programaId", list.get(3).programaId));
                            }
                        });
                    }
                });
    }

    //viewpage标题
    private List<GetBean.TopTab> topTabList = new ArrayList<>();//fragments集合
    private List<CommFragmentImpl> fragments = new ArrayList<>();

    private int headImg;

    //首页最下栏目数据
    private void lastData() {
        //底部广告图
        getLastImg();
        Netword.getInstance().getApi(HomeApi.class)
                .lastTabList()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<GetBean>(getActivity()) {
                    @Override
                    public void successed(GetBean result) {
                        hideWaitDialog();
                        if (result == null) return;
                        GetBean.TopTab topTab = new GetBean.TopTab();
                        topTab.rootId = -1;
                        topTab.rootName = "全部";
                        topTabList.add(topTab);
                        List<GetBean.TopTab> tabList = result.tbclassTypeList;
                        if (tabList != null) {
                            topTabList.addAll(tabList);
                        }
//                        initFragment();
                        initTabView();
                    }
                });

    }

    private void getLastImg() {
        HashMap<String, String> map = new HashMap<>();
        map.put("page", 1 + "");           //Integer is_official   精选传1,其他不传
        map.put("classTypeId", 1 + "");

        Netword.getInstance().getApi(HomeApi.class)
                .homeLastProgram(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<HomeLastProgramBean>(getActivity()) {
                    @Override
                    public void successed(HomeLastProgramBean result) {
                        //轮播图图片数据集合
                        List<HomeLastProgramBean.programaBean.ListBean> list1 = result.programa.indexBannerList;/*
                            List<String> imgList = new ArrayList<>();
                            for (int i = 0; i < list1.size(); i++) {
                                imgList.add(list1.get(i).img);
                            }*/
                        if (list1.get(0).img != null)
                            Glide.with(getActivity()).load(list1.get(0).img).into(homeLastImg);
                    }
                });
    }

    private HomeRecyclerAdapter mAdapter;
    private List<HomeLastProgramBean.ListBean> productList = new ArrayList<>();
    private int page = 1;
    private int rootId = -1;

    private void initTabView() {
        initRecyclerData();
        for (int i = 0; i < topTabList.size(); i++) {
            TabLayout.Tab tab = tablayoutHome.newTab();
            tab.setText(topTabList.get(i).rootName).setTag(i);
            tablayoutHome.addTab(tab);
        }
        //设置tablout 滑动模式
        tablayoutHome.setTabMode(TabLayout.MODE_SCROLLABLE);
        tablayoutHome.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int postion = (int) tab.getTag();
                rootId = topTabList.get(postion).rootId;
                page = 1;
                initRecyclerData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    private void initFragment() {

        for (GetBean.TopTab tab : topTabList) {
            fragments.add((CommFragmentImpl) setTitle(new CommFragmentImpl(), tab.rootId, tab.rootName));
        }

        //设置适配器
        MyPaperAdapter myPaperAdapter = new MyPaperAdapter(getFragmentManager());
        vpHome.setAdapter(myPaperAdapter);
        //设置tablout 滑动模式
        tablayoutHome.setTabMode(TabLayout.MODE_SCROLLABLE);
        tablayoutHome.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                ToastManager.getInstance().showShortToast("onTabSelected");
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        //联系tabLayout和viwpager
        tablayoutHome.setupWithViewPager(vpHome);
        vpHome.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                index = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 设置头目
     */
    private Fragment setTitle(Fragment fragment, int rootId, String title) {
        Bundle args = new Bundle();
        args.putInt(LeCommon.KEY_ROOT_ID, rootId);
       /* sparseArray.put(tempPageIndex++, page);*/
//        args.putInt(LeCommon.KEY_INDEX,index++);
        args.putString("title", title);
        fragment.setArguments(args);
        return fragment;
    }


    /**
     * 适配器
     */
    public class MyPaperAdapter extends FragmentPagerAdapter {

        public MyPaperAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
//            index = position;

            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return topTabList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return topTabList.get(position).rootName;
        }
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            int high = v.findViewById(gaotu).getTop();
                            refreshScrollView.getRefreshableView().smoothScrollTo(0, high + 20);
                        }
                    }).start();
                    break;
                default:
                    break;
            }

        }
    };

    @OnClick({R.id.tv_search, R.id.iv_top, R.id.iv_tryAgain, R.id.tv_sign})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //搜索
            case R.id.tv_search:
                startActivity(new Intent(getActivity(), SearchActivity.class));
                break;
            //底部跳转到顶部的按钮
            case R.id.iv_top:

                tablayoutHome.setVisibility(View.GONE);
                homeLastImg.setVisibility(View.VISIBLE);
                llProgram.setVisibility(View.VISIBLE);
                rvBanner.setVisibility(View.VISIBLE);
                gvKind.setVisibility(View.VISIBLE);
                isVisible = false;


                scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        //  scrollView.fullScroll(ScrollView.FOCUS_DOWN);滚动到底部
                        //  scrollView.fullScroll(ScrollView.FOCUS_UP);滚动到顶部
                        //  需要注意的是，该方法不能直接被调用
                        //  因为Android很多函数都是基于消息队列来同步，所以需要异步操作，
                        //  addView完之后，不等于马上就会显示，而是在队列中等待处理，如果立即调用fullScroll， view可能还没有显示出来，所以会失败
                        //  应该通过handler在新线程中更新
                        scrollView.fullScroll(ScrollView.FOCUS_UP);
                    }
                });
                ivTop.setVisibility(View.GONE);
                break;
            case R.id.iv_tryAgain:
                showWaitDialog("");
                //刷新数据

                //清空商品集合
                // TODO: 2017/10/16
                /*if (lastProgramList != null)
                    lastProgramList.clear();*/
                getData();
                break;
            case R.id.tv_sign:
                if (se.getBoolean(LeCommon.KEY_HAS_LOGIN, false))
                    startActivityForResult(new Intent(getActivity(), SigneActivity.class), 1);
                else {
                    ToastManager.getInstance().showShortToast("您需要先登陆");
                }
                break;
            default:
                break;
        }
    }


    /**
     * ScrollView 的顶部，底部判断：
     * 其中getChildAt表示得到ScrollView的child View， 因为ScrollView只允许一个child
     * view，所以contentView.getMeasuredHeight()表示得到子View的高度,
     * getScrollY()表示得到y轴的滚动距离，getHeight()为scrollView的高度。
     * 当getScrollY()达到最大时加上scrollView的高度就的就等于它内容的高度了
     */
    private void doOnBorderListener() {
        // 底部判断
        if (contentView != null
                && contentView.getMeasuredHeight() <= scrollView.getScrollY()
                + scrollView.getHeight()) {
            ivTop.setVisibility(View.VISIBLE);
        }
        // 顶部判断
        else if (scrollView.getScrollY() == 0) {
            ivTop.setVisibility(View.GONE);
            //Log.i(TAG, "top");
        } else if (scrollView.getScrollY() > 30) {
            ivTop.setVisibility(View.VISIBLE);
        }

    }

    private int index = 0;
    private SparseArray<Integer> sparseArray = new SparseArray<>();
    //刷新加载
    private PullToRefreshBase.OnRefreshListener2 refresh = new PullToRefreshBase.OnRefreshListener2() {

        @Override
        public void onPullDownToRefresh(PullToRefreshBase refreshView) {

            if (Utils.isNetworkAvailable(getActivity())) {
                refreshScrollView.setVisibility(View.VISIBLE);
                llNoNet.setVisibility(View.GONE);
                // 显示最后更新的时间
                //refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                showWaitDialog("");
                //获取首页轮播图数据
                getHomeBannerData();
                //首页分类数据
                getHomeKindData();
                //首页滚动文字数据
                // getHomeScrollTextView();
                //首页2个图片栏目数据
                getHomeProgram();
                //首页最下栏目数据
                if (fragments.size() > 0) {
                    CommFragmentImpl fragment = fragments.get(index);
                    fragment.onPullDownToRefreshData(1);
                }
                refreshScrollView.onRefreshComplete();
                hideWaitDialog();
            } else {
                llNoNet.setVisibility(View.VISIBLE);//刷新重试
                refreshScrollView.setVisibility(View.GONE);
                showShortToast(getString(R.string.net_error));
                hideWaitDialog();
            }

        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase refreshView) {
            // 显示最后更新的时间
            //refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
//            if (fragments.size() > 0) {
//                CommFragmentImpl fragment = fragments.get(index);
//                fragment.notifyChildPagerLoadData();
//            }
            page++;
            initRecyclerData();
            refreshScrollView.onRefreshComplete();
        }
    };

    private Subscription subscribe;

    private void initRecyclerData() {
        final HashMap<String, String> map = new HashMap<>();
        map.put("page", page + "");
        if (rootId != -1) {  //Integer classTypeId   分类id,精选不传
            map.put("classTypeId", rootId + "");
        } else {             //Integer is_official   精选传1,其他不传
            map.put("is_official", 1 + "");
        }
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        final int isAgencyStatus = sp.getInt("isAgencyStatus", 0);
        subscribe = Netword.getInstance().getApi(HomeApi.class)
                .homeLastProgram(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ResultBack<HomeLastProgramBean>(getActivity()) {
                    @Override
                    public void successed(HomeLastProgramBean result) {

                        if (result == null) return;
                        if (page == 1 && productList != null) {
                            productList.clear();
                        }
                        List<HomeLastProgramBean.ListBean> list = result.productList;
                        productList.addAll(list);
                        if (page > 1 && list.isEmpty()) {
                            Utils.show(getActivity(), "亲,已经到底了~");
                            return;
                        }
                        if (mAdapter == null) {
                            mAdapter = new HomeRecyclerAdapter(productList, getContext(), isAgencyStatus);
                            rvHome.setLayoutManager(new LinearLayoutManager(getContext()));
                            rvHome.setAdapter(mAdapter);
                            mAdapter.setOnItemClickLitener(new HomeRecyclerAdapter.OnItemClickLitener() {
                                @Override
                                public void onItemClick(View view, int position) {
                                    startActivity(new Intent(getActivity(), ProductDetailsActivity.class)
                                            .putExtra("productUrl", productList.get(position).tbPrivilegeUrl)
                                            .putExtra("alipayItemId", productList.get(position).alipayItemId)
                                            .putExtra("nowPrice", productList.get(position).preferentialPrice)
                                            .putExtra("price", productList.get(position).price + ""));
                                }
                            });
                            rvHome.setNestedScrollingEnabled(false);
                        } else {
                            mAdapter.notifyDataSetChanged();
                        }
                        hideWaitDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();
                    }
                });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (subscribe != null && !subscribe.isUnsubscribed()) {
            subscribe.unsubscribe();
        }
        unbinder.unbind();
    }

}

